package com.hsd.znsh.service.impl;

import com.hsd.znsh.converter.FunctionConverter;
import com.hsd.znsh.entity.Function;
import com.hsd.znsh.entity.Role;
import com.hsd.znsh.entity.RoleFunction;
import com.hsd.znsh.repository.FunctionRepository;
import com.hsd.znsh.repository.RoleFunctionRepository;
import com.hsd.znsh.repository.RoleRepository;
import com.hsd.znsh.repository.UserRoleRepository;
import com.hsd.znsh.service.RoleService;
import com.hsd.znsh.utils.HqlUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/*
 * @auther: wangjiacai
 *
 * @create: 2018-05-09 14:47:58
 */
@Service
public class RoleServiceImpl extends BaseServiceImpl implements RoleService {

    @Autowired
    private RoleRepository roleRepository;

    @Autowired
    private FunctionRepository functionRepository;

    @Autowired
    private RoleFunctionRepository roleFunctionRepository;

    @Autowired
    private UserRoleRepository userRoleRepository;

    @Override
    public long getRoleListTotalPages(Role role) {
        return this.count(HqlUtil.getCountHql(role),role);
    }

    @Override
    public List<Role> getRoleList(Role role, Pageable pageable) {
        return this.find(HqlUtil.getQueryHql(role),role,pageable);
    }

    @Override
    public List<Map> getFunctionTree() {
        List<Function> list=functionRepository.findAll();
        return FunctionConverter.converterToMapList(list);
    }

    @Override
    public void assignRoleFunction(String functionIds, Integer roleId) {
        roleFunctionRepository.deleteByRoleId(roleId);
        for(String functionId:functionIds.split(",")){
            RoleFunction roleFunction=new RoleFunction();
            roleFunction.setFunctionId(Integer.parseInt(functionId));
            roleFunction.setRoleId(roleId);
            roleFunctionRepository.save(roleFunction);
        }
    }

    @Override
    public Role addRole(Role role) {
        return roleRepository.save(role);
    }

    @Override
    public void deleteRole(Integer id) {
        roleFunctionRepository.deleteByRoleId(id);
        userRoleRepository.deleteByRoleId(id);
        roleRepository.delete(id);
    }
}
